package com.shanghaionstar.utils;

import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.webkit.WebView;

import com.alipay.sdk.app.PayTask;
import com.alipay.sdk.util.H5PayResultModel;
import com.onstar.cn.common.log.LogManager;

import java.lang.ref.WeakReference;

/**
 * web调起支付功能
 * <p>
 * Created by Yonglang Hong on 2017/5/16.
 */
public class AliPayByWebUtil {

    private Activity activity;

    private WebView webView;

    private PayHandler payHandler;

    public AliPayByWebUtil(@NonNull Activity activity, @NonNull WebView webView) {
        this.activity = activity;
        this.webView = webView;
    }

    /**
     * 在webview WebViewClient的shouldOverrideUrlLoading方法中直接调用该方法支付
     * @param url：支付链接
     */
    public boolean pay(String url) {
        boolean isPay = false;
        final PayTask task = new PayTask(activity);
        //处理订单信息
        final String ex = task.fetchOrderInfoFromH5PayUrl(url);
        if (!TextUtils.isEmpty(ex)) {
            isPay = true;
            //调用支付接口进行支付
            new Thread(new Runnable() {
                public void run() {
                    H5PayResultModel result = task.h5Pay(ex, true);
                    //处理返回结果
                    if (!TextUtils.isEmpty(result.getReturnUrl())) {
                        LogManager.getInstance(activity).d("result:" + result.getResultCode() + ",  url = " + result.getReturnUrl());
                        if ("9000".equals(result.getResultCode())) {
                            Message message = new Message();
                            message.obj = result.getReturnUrl();
                            message.what = 0;
                            getPayHandler().sendMessage(message);
                        }
//                                webView.loadUrl(result.getReturnUrl());
                    }
                }
            }).start();
        }
        return isPay;
    }

    private PayHandler getPayHandler() {
        if (payHandler == null) {
            payHandler = new PayHandler(this);
        }
        return payHandler;
    }

    /**
     * 支付成功后继续调用支付成功页面
     */
    static class PayHandler extends Handler {

        private WeakReference<AliPayByWebUtil> activityWeakReference;

        public PayHandler(AliPayByWebUtil util) {
            this.activityWeakReference = new WeakReference<>(util);
        }

        @Override
        public void handleMessage(Message msg) {
            if (activityWeakReference.get().activity != null) {
                if (msg.what == 0)
                    activityWeakReference.get().webView.loadUrl((String) msg.obj);
            }
        }
    }
}
